/**
 * Copyright 2007-2008. Chongqing First Information & Network Co., Ltd. All
 * rights reserved. <a>http://www.cqfirst.com.cn</a>
 */
package com.cqcis.uip.base.framework.utils;

import java.util.concurrent.ThreadPoolExecutor;

import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.support.AbstractIoFilterChain;
import org.apache.mina.filter.executor.ExecutorFilter;

/**
 * 采用线程池的应用过滤器
 * 
 * @author huangmy
 * @date 2007-12-29
 */
public class ApplicationExecutorFilter extends ExecutorFilter {
	private String name; 
	
	@Override
	public void sessionCreated(NextFilter nextFilter, IoSession session) {
		ConnectFuture future = (ConnectFuture) session
				.removeAttribute(AbstractIoFilterChain.CONNECT_FUTURE);
		if (future != null) {
			future.setSession(session);
		}
		super.sessionCreated(nextFilter, session);
	}

	@Override
	public void sessionOpened(NextFilter nextFilter, IoSession session) {
		ConnectFuture future = (ConnectFuture) session
				.removeAttribute(AbstractIoFilterChain.CONNECT_FUTURE);
		if (future != null) {
			future.setSession(session);
		}
		super.sessionOpened(nextFilter, session);
	}

	public ApplicationExecutorFilter(
			ThreadPoolExecutor applicationFilterExecutor, String name) {
		super(applicationFilterExecutor, name);
		this.name = name;
	}

	public void filterClose(NextFilter nextFilter, IoSession session)
			throws Exception {
		SessionUtil.setClosedByService(session); // 主动关闭
		super.filterClose(nextFilter, session);
	}

	public String getName() {
		return name;
	}
}